# coding: utf-8

from leancloud import Object
from leancloud import File
from leancloud import Query
from leancloud import LeanCloudError
from flask import Blueprint
from flask import request
from flask import redirect
from flask import url_for
from flask import render_template
import os
from flask import Flask
from werkzeug.utils import secure_filename
from StringIO import StringIO
from io import BytesIO

UPLOAD_FOLDER = '/tmp'     #leancloud engine 中,只有tmp目录下是具有可读功能的


class Carousel(Object):
    pass

upload_view = Blueprint('upload', __name__)


@upload_view.route('')
def show():
    try:
        carousels = Query(Carousel).descending('createdAt').find()
    except LeanCloudError, e:
        if e.code == 101:  # 服务端对应的 Class 还没创建
            carousels = []
        else:
            raise e
    return render_template('upload.html', carousels=carousels)


@upload_view.route('', methods=['POST'])
def add():
    delCarousel()
    for i in range(1, 4):
        upload("img"+str(i),"title"+str(i))
    return redirect(url_for('upload.show'))

def upload(img,title):
    fil = request.files[img]
    fname = secure_filename(fil.filename)
    fil.save(os.path.join(UPLOAD_FOLDER, fname))
    file_object = open(UPLOAD_FOLDER+'/'+fname,'r')
    upFile = File(fname,file_object)
    file_object.close()
    os.remove(UPLOAD_FOLDER+'/'+fname)
    upFile.save()
    content = request.form[title]
    carousel = Carousel(content=content)
    carousel.set("img",upFile)
    carousel.save()
    pass

def delCarousel():
    try:
        carousels = Query(Carousel).descending('createdAt').find()
        for carousel in carousels:
            fil = carousel.get("img")
            fil.destroy()
            carousel.destroy()
    except LeanCloudError, e:
        if e.code == 101:  # 服务端对应的 Class 还没创建
            pass
        else:
            raise e